//
//  UserProfileViewController.m
//  WindRunner
//
//  Created by leeqb on 11/9/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "UserProfileViewController.h"
#import "UserEditViewController.h"
#import "AFURLConnectionOperation.h"
#import "AFURLSessionManager.h"
#import "AFHTTPRequestOperationManager.h"
#import "BigImageViewer.h"

@interface UserProfileViewController ()
{
    NSDictionary *_userInfo;
    
    NSArray *_titleArray;
    NSArray *_activityTypeItems;
    NSArray *_feelingItems;
    NSArray *_statureItems;
    NSArray *_hobbyItems;
    NSMutableArray *_picsArray;
    
    BOOL _isPicLoaded;
    BigImageViewer *_imageViewer;
}
@end

@implementation UserProfileViewController

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        _titleArray = @[@"活动类型", @"情感状态", @"身材", @"兴趣爱好", @"生日"];
        _activityTypeItems = @[LocalStringSetting(@"UE_ACTIVITY_TYPE1"), LocalStringSetting(@"UE_ACTIVITY_TYPE2"), LocalStringSetting(@"UE_ACTIVITY_TYPE3"),
                                LocalStringSetting(@"UE_ACTIVITY_TYPE4"), LocalStringSetting(@"UE_ACTIVITY_TYPE5"), LocalStringSetting(@"UE_ACTIVITY_TYPE6"),
                                LocalStringSetting(@"UE_ACTIVITY_TYPE7"), LocalStringSetting(@"UE_ACTIVITY_TYPE8"), LocalStringSetting(@"UE_ACTIVITY_TYPE9"),
                                LocalStringSetting(@"UE_ACTIVITY_TYPE10"), LocalStringSetting(@"UE_ACTIVITY_TYPE11"), LocalStringSetting(@"UE_ACTIVITY_TYPE12"),
                                LocalStringSetting(@"UE_ACTIVITY_TYPE13"), LocalStringSetting(@"UE_ACTIVITY_TYPE14"), LocalStringSetting(@"UE_ACTIVITY_TYPE15"),
                                LocalStringSetting(@"UE_ACTIVITY_TYPE16"), LocalStringSetting(@"UE_ACTIVITY_TYPE17"), LocalStringSetting(@"UE_ACTIVITY_TYPE18"),
                                LocalStringSetting(@"UE_ACTIVITY_TYPE19"), LocalStringSetting(@"UE_ACTIVITY_TYPE20"), LocalStringSetting(@"UE_ACTIVITY_TYPE21"),
                                LocalStringSetting(@"UE_ACTIVITY_TYPE22"), LocalStringSetting(@"UE_ACTIVITY_TYPE23"), LocalStringSetting(@"UE_ACTIVITY_TYPE24")];
        _feelingItems = @[LocalStringSetting(@"UE_FEELING1"), LocalStringSetting(@"UE_FEELING2"), LocalStringSetting(@"UE_FEELING3")];
        _statureItems = @[LocalStringSetting(@"UE_STATURE1"), LocalStringSetting(@"UE_STATURE2"), LocalStringSetting(@"UE_STATURE3")];
        _hobbyItems = @[LocalStringSetting(@"UE_HOBBY1"), LocalStringSetting(@"UE_HOBBY2"), LocalStringSetting(@"UE_HOBBY3")];
        _picsArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _basicInfoTable.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
    
    UIImage *charmImage = [UIImage imageNamed:@"ic_charm.png"];
    UIImage *levelImage = [UIImage imageNamed:@"ic_level.png"];
    CGRect rect = _charmTitleLabel.frame;
    rect.origin.x += rect.size.width + 5;
    rect.size.width = charmImage.size.width / 2.2;
    rect.size.height = charmImage.size.height / 2.2;
    rect.origin.y = (44 - rect.size.height) / 2;
    _charmImageView.frame = rect;
    _charmLabel.frame = rect;
    
    rect = _levelTitleLabel.frame;
    rect.origin.x += rect.size.width + 5;
    rect.size.width = levelImage.size.width / 3;
    rect.size.height = levelImage.size.height / 3;
    rect.origin.y = (44 - rect.size.height) / 2;
    _levelImageView.frame = rect;
    _levelLabel.frame = rect;
    
    // 记录visit表
    if(self.data) {
        NSDictionary *requestData = @{@"userid":self.data[@"id"],
                                      @"guestid":[AuthHelper getCurrentUser][@"id"]};
        FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                                 interface:@"visit"
                                                                    params:requestData];
        [FMNetwork request:requestObj showMask:NO success:^(NSDictionary *data) {
        } falied:^(NSError *error) {
        }];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    if(self.data) {
        _userInfo = self.data;
        UIImage *favoImage = [UIImage imageNamed:@"ic_favo.png"];
        [_rightBarButton setBackgroundImage:favoImage forState:UIControlStateNormal];
        
        CGRect rect = _rightBarButton.frame;
        rect.size.width = favoImage.size.width;
        rect.size.height = favoImage.size.height;
        _rightBarButton.frame = rect;
        _rightBarButton.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 5);
    } else {
        _userInfo = [AuthHelper getCurrentUser];
    }
    
    [self initUI];
    [_basicInfoTable reloadData];
}

// 界面赋值
- (void)initUI
{
    if(_userInfo) {
        self.navigationItem.title = _userInfo[@"account"];
        
        NSInteger sex = [[NSString formatString:_userInfo[@"sex"]] integerValue];
        if(sex == 0) { // 女
            _genderIconView.image = [UIImage imageNamed:@"st_gender_female.png"];
        } else { // 男
            _genderIconView.image = [UIImage imageNamed:@"st_gender_male.png"];
        }
        
        long long birthday = [[NSString formatString:_userInfo[@"birthday"]] longLongValue];
        _ageLabel.text = [NSString stringWithFormat:@"%@", @([FMCommonFun getYearIntervalFromTimestamp:birthday])];
        _starLabel.text = [NSString formatString:_userInfo[@"constellation"]];
        
        NSString *lastLocationX = [NSString formatString:_userInfo[@"lastlocationX"]];
        NSString *lastLocationY = [NSString formatString:_userInfo[@"lastlocationY"]];
        if(![lastLocationX isEqual:[NSNull null]] && ![lastLocationY isEqual:[NSNull null]]) {
            _distanceLabel.text = [NSString stringWithFormat:@"%.1f",
                                   [FMCommonFun distanceBetweenOrderBy:CURR_COORDINATE_X
                                                                      :[lastLocationX doubleValue]
                                                                      :CURR_COORDINATE_Y
                                                                      :[lastLocationY doubleValue]]];
        }
        _idLabel.text = [NSString stringWithFormat:@"风行者ID：%@", [NSString formatString:[AuthHelper getCurrentUser][@"id"]]];
        
        [_headIcon showInCircle];
        LEDownloadManager *downloadManager = [[LEDownloadManager alloc] initWithTarget:_headIcon];
        [downloadManager downLoadImageWithURL:[NSString formatString:_userInfo[@"headicon"]] imagetype:@"UserProfileImages"];
        
        if(!_isPicLoaded) {
            NSDictionary *requestData = @{@"userid":_userInfo[@"id"],
                                          @"pageindex":@"1",
                                          @"pagesize":@"50"};
            FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                                     interface:@"userpicture"
                                                                        params:requestData];
            [FMNetwork request:requestObj showMask:NO success:^(NSDictionary *data) {
                _isPicLoaded = YES;
                _picsArray = [data[@"record"][@"data"] mutableCopy];
                if([_picsArray count] > 8) {
                    _picCollectionView1.hidden = YES;
                }
                [_picCollectionView reloadData];
            } falied:^(NSError *error) {
            }];
        }
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"segUserEdit"]) {
        UserEditViewController *vc = (UserEditViewController *)segue.destinationViewController;
        vc.data = _userInfo;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(collectionView.tag == 1) {
        return [_picsArray count];
    } else {
        return 8;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(66, 66);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
    cell.backgroundColor = RGB(44, 44, 44);
    cell.layer.cornerRadius = 11;
    
    if(collectionView.tag == 1) {
        id picObj = nil;
        @try {
            picObj = _picsArray[indexPath.row];
        }
        @catch (NSException *exception) {
            picObj = [UIImage imageNamed:@"ic_header_def.png"];
        }
        @finally {
            UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
            if([picObj isKindOfClass:[NSDictionary class]]) {
                imageView.image = [UIImage imageNamed:@"ic_header_def.png"];
                LEDownloadManager *downloadManager = [[LEDownloadManager alloc] initWithTarget:imageView];
                [downloadManager downLoadImageWithURL:[NSString formatString:picObj[@"url"]] imagetype:@"UserProfileImages"];
            } else if([picObj isKindOfClass:[UIImage class]]) {
                imageView.image = (UIImage *)picObj;
            }
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == 1) {
        switch (indexPath.row) {
            case 0:
                return 162;
            case 1:
                return 0;
            case 2:
                return 20;
            case 3:
                return 40;
            case 4:
                return 222;
        }
    } else if(tableView.tag == 2) {
        return 38;
    }
    
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag == 1) {
        return 5;
    } else if(tableView.tag == 2) {
        return 5;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if(tableView.tag == 1) {
        if(indexPath.row == 0) {
            return _collectionCell;
        } else if(indexPath.row == 1) {
            return _levelCell;
        } else if(indexPath.row == 2) {
            return _spaceCell;
        } else if(indexPath.row == 3) {
            return _recentAccessCell;
        } else if(indexPath.row == 4) {
            return _basicCell;
        }
    } else if(tableView.tag == 2) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"BasicDetailCell"];
        
        UILabel *titleLabel = (UILabel *)[cell viewWithTag:1];
        UILabel *valueLabel = (UILabel *)[cell viewWithTag:2];
        
        titleLabel.text = _titleArray[indexPath.row];
        valueLabel.text = @"无";
        NSInteger arrayIdx = -1;
        switch (indexPath.row) {
            case 0:
            {
                if(![[NSString formatString:_userInfo[@"activetype"]] isEqualToString:@""]) {
                    arrayIdx = [[NSString formatString:_userInfo[@"activetype"]] integerValue];
                    @try {
                        valueLabel.text = _activityTypeItems[arrayIdx];
                    }
                    @catch (NSException *exception) {
                    }
                    @finally {
                    }
                }
                break;
            }
            case 1:
            {
                if(![[NSString formatString:_userInfo[@"emotion"]] isEqualToString:@""]) {
                    arrayIdx = [[NSString formatString:_userInfo[@"emotion"]] integerValue];
                    @try {
                        valueLabel.text = _feelingItems[arrayIdx];
                    }
                    @catch (NSException *exception) {
                    }
                    @finally {
                    }
                }
                break;
            }
            case 2:
            {
                NSString *heightStr = [NSString formatString:_userInfo[@"height"]];
                NSString *weightStr = [NSString formatString:_userInfo[@"weight"]];
                NSMutableString *temp = [NSMutableString string];
                
                if(![heightStr isEqualToString:@""]) {
                    [temp appendFormat:@"%@cm ", heightStr];
                }
                
                if(![weightStr isEqualToString:@""]) {
                    [temp appendFormat:@"%@kg ", weightStr];
                }
                
                if(![[NSString formatString:_userInfo[@"body"]] isEqualToString:@""]) {
                    arrayIdx = [[NSString formatString:_userInfo[@"body"]] integerValue];
                    @try {
                        [temp appendString:_statureItems[arrayIdx]];
                    }
                    @catch (NSException *exception) {
                    }
                    @finally {
                    }
                }
                
                if(![temp isEqualToString:@""]) {
                    valueLabel.text = temp;
                } else {
                    valueLabel.text = @"无";
                }
                break;
            }
            case 3:
            {
                if(![[NSString formatString:_userInfo[@"interests"]] isEqualToString:@""]) {
                    arrayIdx = [[NSString formatString:_userInfo[@"interests"]] integerValue];
                    @try {
                        valueLabel.text = _hobbyItems[arrayIdx];
                    }
                    @catch (NSException *exception) {
                    }
                    @finally {
                    }
                }
                break;
            }
            case 4:
            {
                NSString *birthDateStr = [NSString formatString:_userInfo[@"birthday"]];
                if(![birthDateStr isEqualToString:@""]) {
                    NSDate *birthDate = [NSDate dateWithTimeIntervalSince1970:[birthDateStr doubleValue]/1000];
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    dateFormatter.dateFormat = @"yyyy/MM/dd";
                    valueLabel.text = [dateFormatter stringFromDate:birthDate];
                }
                break;
            }
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if(tableView.tag == 1) {
        if(indexPath.row == 3) {
            [self performSegueWithIdentifier:@"segRecentAccess" sender:self];
        }
    }
}

// 点击显示大图片
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView.tag == 1) {
        _imageViewer = [[BigImageViewer alloc] init];
        _imageViewer.picArray = _picsArray;
        _imageViewer.currIndex = indexPath.row;
        _imageViewer.catchDirectory = @"UserProfileImages";
        [_imageViewer show];
    }
}

- (IBAction)rightBarClicked:(id)sender {
    if(self.data) {
        // 收藏用户
        NSDictionary *requestData = @{@"userid":[AuthHelper getCurrentUser][@"id"],
                                      @"friendid":self.data[@"id"]};
        FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                                 interface:@"useraddfavor"
                                                                    params:requestData];
        [FMNetwork request:requestObj showMask:YES success:^(NSDictionary *data) {
            [FMToast showMessage:LocalStringCommon(@"OPER_SUCC")];
        } falied:^(NSError *error) {
        }];
    } else {
        [self performSegueWithIdentifier:@"segUserEdit" sender:nil];
    }
}

- (IBAction)takePhoto:(UIButton *)sender {
    PickImageView *pickView = [[PickImageView alloc] init];
    pickView.delegate = self;
    [pickView show];
}

- (void)imageTypeSelected:(UIImagePickerController *)vc
{
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:^{
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    [_picsArray addObject:editedImage];
    if([_picsArray count] > 8) {
        _picCollectionView1.hidden = YES;
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        // 上传照片到服务器
        [_picCollectionView reloadData];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString *urlString = [NSString stringWithFormat:@"%@addpicture", BASE_API_URL_WINDRUNNER];
            NSDictionary *requestData = @{@"userid":[AuthHelper getCurrentUser][@"id"]};
            
            AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
            httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];;
            
            NSData *imageData = UIImagePNGRepresentation(editedImage);
            NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:requestData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                if(imageData) {
                    [formData appendPartWithFileData:imageData name:@"url" fileName:@"PictureWallImage.png" mimeType:@"image/png"];
                }
            } error:nil];
            [request setTimeoutInterval:5];
            
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            NSProgress *progress = nil;
            
            //[FMToast showMessage:LocalStringCommon(@"OPER_DOING")];
            NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                if(!error) {
                    //[FMToast showMessage:LocalStringCommon(@"OPER_SUCC")];
                } else {
                    [FMToast showMessage:LocalStringCommon(@"OPER_FAIL")];
                }
            }];
            
            [uploadTask resume];
        });
    }];
}

@end
